package tool

import (
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
	"strings"
)

// fileName 日志文件名，不需要带.log
// logLevel 日志级别
// size 文件最大多少MB
// sum 最多保留数量
// age 保留最长天数
// comp 是否压缩
func New(fileName string, logLevel string, size, sum, age int, comp bool) *zap.SugaredLogger {
	// 设置路径
	if ok := strings.Contains(fileName, "."); !ok {
		fileName = fileName + ".log"
	}
	path := "/logs/" + fileName
	if logPath, ok := os.LookupEnv("LOG_PATH"); ok {
		path = logPath + "/" + fileName
	}

	hook := lumberjack.Logger{
		Filename:   path, // 日志文件路径
		MaxSize:    size, // MB megabytes,默认128
		MaxBackups: sum,  // 最多保留备份,默认30
		MaxAge:     age,  // days,默认30
		Compress:   comp, // 是否压缩 disabled by default
	}

	w := zapcore.AddSync(&hook)

	// 设置日志级别,debug可以打印出info,debug,warn；info级别可以打印warn，info；warn只能打印warn
	// debug->info->warn->error
	var level zapcore.Level
	switch logLevel {
	case "debug":
		level = zap.DebugLevel
	case "warn":
		level = zap.WarnLevel
	case "error":
		level = zap.ErrorLevel
	default:
		level = zap.InfoLevel
	}
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
	// 时间格式
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	core := zapcore.NewCore(
		zapcore.NewConsoleEncoder(encoderConfig),
		w,
		level,
	)

	logger := zap.New(core)

	return logger.Sugar()
}
